<template>
  <div class="authority">
    <div class="gva-search-box">
      <el-form ref="searchForm" :inline="true">
        <el-form-item label="驱动名称">
          <el-input v-model="searchInfo.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="上传时间">
          <el-date-picker v-model="searchInfo.time" type="daterange" range-separator="-" start-placeholder="开始时间"
            end-placeholder="结束时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width:400px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">
            查询
          </el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box unit">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="addUnit">新增</el-button>
      </div>
      <div class="ant-alert-info">
        <el-popover placement="left-start" :width="350" trigger="click" transition='el-zoom-in-left'>
          <div class="pop-content">
            <div class="pop-title">自定义列</div>
            <div class="check-list">
              <el-checkbox-group v-model="checkedColumns" @change="handleColumnsChange">
                <el-checkbox v-for="column in columns" :value="column" :label="column"></el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
          <template #reference>
            <div class="anticon">
              <el-icon size="16" color="#1890ff">
                <Setting />
              </el-icon>
              <div style="margin-left: 2px;">自定义列</div>
            </div>
          </template>
        </el-popover>
      </div>
      <el-table :data="tableData" row-key="id">
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column align="left" label="驱动名称" prop="name" v-if="checkedColumns.includes('驱动名称')"></el-table-column>
        <el-table-column align="left" label="驱动类型" prop="type" v-if="checkedColumns.includes('驱动类型')">
          <template #default="scope">
            <span>{{ qdCate[scope.row.type-1].label }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="上传时间" v-if="checkedColumns.includes('上传时间')">
          <template #default="scope">
            <span>{{ formatTimestamp(scope.row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="下载次数" prop="downloadTimes"
          v-if="checkedColumns.includes('下载次数')"></el-table-column>
        <el-table-column align="left" fixed="right" label="操作" min-width="80" v-if="checkedColumns.includes('操作')">
          <template #default="scope">
            <el-button type="primary" link icon="edit" @click="editUnit(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link icon="delete" @click="delUnit(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination v-model:current-page="page" :page-size="pageSize" :total="total" layout="prev, pager, next"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <el-drawer v-model="dialogFormVisible" :size="1000" :before-close="handleClose" :show-close="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{ dialogTitle }}</span>
          <div>
            <el-button @click="closeDialog">取消</el-button>
            <el-button type="primary" @click="enterDialog">确定</el-button>
          </div>
        </div>
      </template>
      <el-form v-if="dialogFormVisible" ref="yyglForm" label-width="150" :model="form" :rules="rules">
        <el-form-item label="驱动类别" prop="type">
          <el-radio-group v-model="form.type" class="ml-4">
            <el-radio v-for="item in qdCate" :value="item.value" size="large">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="驱动文件" prop="url" style="align-items: normal;">
          <el-upload v-model:file-list="fileList" :action="adminUrl"
            :on-success="uploadSuccess" :headers="headerOdj" :on-change="handleChange">
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>
<script setup>
import {
  getQdList,
  updateQd,
  createQd,
  deleteQd
} from '@/api/xitongpeizhi'

import { reactive, ref, onMounted } from 'vue'
import { useAppStore } from "@/pinia";
import { useUserStore } from '@/pinia/modules/user'
import { countdownEmits, ElMessage, ElMessageBox, useFormItem } from 'element-plus'
import { formatTimestamp } from '@/utils/format'
const { formItem } = useFormItem()

defineOptions({
  name: 'Yygl'
})
const appStore = useAppStore()
const form = ref({
   name:'',
   type:1,
   url:''
})

const searchInfo = ref({
  name: '',
  time: [],
  timeStart: '',
  timeEnd: ''
})

const userStore = useUserStore()
const headerOdj = ref({ token: userStore.token })
const adminUrl = ref('')
adminUrl.value = import.meta.env.VITE_BASE_PATH + '/file/upload'
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const dialogFormVisible = ref(false)
let validateImage = (rule, value, callback) => {
  if (!form.value.url||fileList.value.length==0) {
    callback(new Error('请上传文件'))
  } else {
    callback()
  }
}
const rules = reactive({
  type: [{ required: true, message: '请选择驱动类型', trigger: 'change' }],
  url: [{ required: true, validator: validateImage, trigger: 'change' }],
})

const yyglForm = ref(null)

const initForm = () => {
  yyglForm.value.resetFields()
  form.value = {
    name:'',
   type:1,
   url:''
  }
  fileList.value = []
}

const checkedColumns = ref(['序号', '驱动名称', '驱动类型', '上传时间', '下载次数', '操作'])

if (localStorage.getItem('columnData') && JSON.parse(localStorage.getItem('columnData')).qdwj) {
  checkedColumns.value = JSON.parse(localStorage.getItem('columnData')).qdwj
}
const columns = ref(['序号', '驱动名称', '驱动类型', '上传时间', '下载次数', '操作'])
const handleColumnsChange = (val) => {
  let obj = {

  }
  if (localStorage.getItem('columnData')) {
    obj = JSON.parse(localStorage.getItem('columnData'))
  }
  obj.qdwj = val
  localStorage.setItem('columnData', JSON.stringify(obj))
}
const isEdit = ref(false)
const dialogTitle = ref('新增文件')
const addUnit = () => {
  dialogTitle.value = '新增文件'
  isEdit.value = false
  dialogFormVisible.value = true
}
const closeDialog = () => {
  initForm()
  dialogFormVisible.value = false
}

const handleClose = (done) => {
  initForm()
  done()
}
const handleUserClose = (done) => {
  initUserForm()
  done()
}
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}
const tableData = ref([])
// 查询
const getTableData = async () => {
  const res = await getQdList({
    pageNumber: page.value,
    pageSize: pageSize.value,
    ...searchInfo.value
  })
  if (res.code == 200) {
    tableData.value = res.result.data
    total.value = res.result.total
  }
}
getTableData()
const qdCate = ref([
  {
    label: '统信UOS',
    value: 1
  },
  {
    label: '银河麒麟',
    value: 2
  },
  {
    label: '中标麒麟',
    value: 3
  },
  {
    label: 'Windows',
    value: 4
  }
])

onMounted(() => {

})

const enterDialog = async () => {
  yyglForm.value.validate(async (valid) => {
    if (valid) {
      form.value.name=fileList.value[0].name
      let res
      if (isEdit.value) {
        res = await updateQd(form.value)
      } else {
        res = await createQd(form.value)
      }
      if (res.code == 200) {
        ElMessage({
          type: 'success',
          message: isEdit.value ? '编辑成功' : '添加成功!'
        })
        getTableData()
      }
      initForm()
      dialogFormVisible.value = false
    }
  })
}
const editUnit = async (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑驱动'
  form.value = JSON.parse(JSON.stringify(row))
  if (form.value.url) {
    fileList.value = [{
      name: form.value.name,
      url: form.value.url
    }]
  }
  form.value.fileId = form.value.id
  dialogFormVisible.value = true
}
const delUnit = (row) => {
  ElMessageBox.confirm(
    '确认删除?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    const res = await deleteQd(row.id)
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      getTableData()
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}
const onSubmit = () => {
  page.value = 1
  searchInfo.value.timeStart = searchInfo.value.time[0]
  searchInfo.value.timeEnd = searchInfo.value.time[1]
  getTableData()
}
const onReset = () => {
  searchInfo.value = {
    name: '',
    time: [],
    timeStart: '',
    timeEnd: ''
  }
  getTableData()
}
const fileList = ref([])
const handleRemove = (file) => {
  fileList.value = []
  form.value.ico = ''
}

const uploadSuccess = async (res) => {
  if (res.code != 200) {
    ElMessage({
      type: 'warning',
      message: res.message
    })
    fileList.value.pop()
    return
  }
  form.value.url = res.result
  yyglForm.value.validateField('url')
}

const handleChange = (uploadFile, uploadFiles) => {
 
}

</script>

<style lang="scss">
.flex {
  .area {
    flex: 2;
    background-color: #fff;
    margin: 0.5rem 20px 0.5rem 0;
  }

  .unit {
    flex: 4;
  }
}

.ant-alert-info {
  display: flex;
  justify-content: end;
  align-items: center;
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
  color: #1890ff;
  padding: 5px;

  .anticon {
    display: flex;
    align-items: center;
    cursor: pointer;
  }
}

.btns {
  display: flex;
}

.section-title {
  font-weight: bold;
  font-size: 20px;
  line-height: 33px;
  padding: 8px 0 4px 14px;
  color: #4E7DFD;
  position: relative;
}

.section-title:before {
  content: '';
  position: absolute;
  top: 17px;
  left: 0;
  width: 6px;
  height: 14px;
  border-radius: 3px;
  background: #4E7DFD;
}

.tips {
  margin-bottom: 20px;
  color: #ff6666;
  margin-left: 10px;
}
</style>
